package com.shadow.baiqun.delegate.room.check;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.room.adapter.CheckAdapter;
import com.shadow.baiqun.delegate.room.goodsclassify.GoodsClassifyDelegate;
import com.shadow.baiqun.event.RefreshCheckTaskEvent;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.event.StartBrotherFragmentEvent;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.ui.recycler.BaseDecoration;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zy
 * on 2018/6/19
 * 检测
 */
public class CheckDelegate extends RxShadowDelegate {

    public static CheckDelegate create() {
        final CheckDelegate contentDelegate = new CheckDelegate();
        final Bundle bundle = new Bundle();
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.swipe_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    private CheckAdapter mAdapter;
    private boolean isRequesting = false;
    private static final int PAGE_SIZE = 50;
    private int mNextRequestPage = 1;

    @Override
    public Object setLayout() {
        return R.layout.delegate_room_check;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        List<String> list = new ArrayList<>();
        list.add("总量/已完成量");
        list.add("添加人");
        list.add("时间");
        mHeadView.setHeaders(list);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        mAdapter = new CheckAdapter(R.layout.item_room_check, null);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white_light_gray), 1));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity itemEntity = (MultipleItemEntity) adapter.getItem(position);
                if (itemEntity != null) {
                    final CheckTaskEntity checkTaskEntity = itemEntity.getField(ItemField.ITEM_OBJ);
                    if (checkTaskEntity != null) {
                        new OperationDialog(getContext(), new OperationDialog.OnActionListener() {

                            @Override
                            public void onOrderComplete() {
                                //货物归位
                                EventBus.getDefault().post(new StartBrotherFragmentEvent
                                        (GoodsClassifyDelegate.create(checkTaskEntity.getId())));
                            }

                            @Override
                            public void onOrderDetail() {
                                //详情
                                EventBus.getDefault().post(
                                        new StartBrotherFragmentEvent(CheckDetailDelegate.create(checkTaskEntity.getId())));
                            }
                        }).show();
                    }
                }
            }
        });
        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
        if (mAdapter.getEmptyView() != null) {
            mAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        EventBus.getDefault().register(this);
    }

    private void loadMore() {
        requestData(false);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        refresh();
    }

    @OnClick(R2.id.btn_reset)
    public void onRefreshData() {
        EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckAddTaskDelegate.create()));
    }

    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }

    }

    private void requestData(final boolean isRefresh) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/indoorTest/taskList")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        CheckTaskDataConverter converter = new CheckTaskDataConverter();
                        converter.setJsonData(response);
                        setData(isRefresh, converter.convert());
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .params("type", 3)
                .params("pageNum", mNextRequestPage)
                .params("pageSize", PAGE_SIZE)
                .build()
                .unRestGet());
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Subscribe
    public void onRefreshEvent(RefreshCheckTaskEvent event) {
        refresh();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
